package com.element.security.resource.context;

import com.common.core.constant.SecurityHeader;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther WuJun.Zhang
 * @date 2022/3/31 下午5:01
 */
public class TokenContext {

    public static String getToken(HttpServletRequest request){
        String header = request.getHeader(SecurityHeader.AUTH_SECURITY_HEADERS);
        if (!StringUtils.hasText(header)) {
            return request.getParameter(SecurityHeader.AUTH_SECURITY_HEADERS);
        }
        if (!header.contains(SecurityHeader.AUTH_SECURITY_VALUE)) {
            return null;
        }
        String authHeaderValue = header.substring(SecurityHeader.AUTH_SECURITY_VALUE.length()).trim();
        request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, header.substring(0, SecurityHeader.AUTH_SECURITY_VALUE.length()).trim());
        int commaIndex = authHeaderValue.indexOf(44);
        if (commaIndex > 0) {
            authHeaderValue = authHeaderValue.substring(0, commaIndex);
        }
        return authHeaderValue;
    }
}